<?php

class CommentController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='application.modules.admin.views.layouts.default';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','test','view','reply','list','batchcomments','batchresource','create','update','iteminfo'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionTest()
	{
		
		$comment = new Comment();
		
		$comment->com_mid = 2;
		$comment->com_rid = 32;
		$comment->com_author = 'admin';
		$comment->com_status = Comment::COMMENT_PUBLISHED;
// 		$comment->com_ip = ip2long('61.135.230.22');
		$comment->com_email = 'dajjwwx@hello.com';
		$comment->com_create = time();
		$comment->com_contents = 'Hello everyone morning';
		
		if ($comment->save())
			echo("OK");
		else {
			echo "false";
		}
			
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->blankLayout();
		
		$model = $this->loadModel($id);
		
 		//UtilTools::dump($model->attributes);
		
		$result = Comment::model()->getComments($model);
		
		//UtilTools::dump($result);
		
		$this->render('view',array(
			'model'=>$result,
		));
	}
	
	public function actionReply($id)
	{
		$this->blankLayout();
		$data = $this->loadModel($id);
		
		if($data->comment)
		{
			echo $id.'#-#';
			$this->render('reply',array(
				'model'=>$data->comment
			));
		}
		else
		{
			echo "false";
		}
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Comment;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		

		if(isset($_POST['Comment']))
		{
			$model->attributes=$_POST['Comment'];
			
			$params = explode(',', $_POST['params']);
			
			$id_1 = explode(':', $params[0]);
			$id_2 = explode(':', $params[1]); 
			
			
			
			if($id_2[0] == 'aid')
				$model->com_aid = $id_2[1];
			elseif ($id_2[0] == 'gid')
				$model->com_gid = $id_2[1];
			elseif ($id_2[0] == 'mid')
				$model->com_mid = $id_2[1];
			elseif ($id_2[0] == 'auid')
				$model->com_auid = $id_2[1];
			elseif ($id_2[0] == 'vid')
				$model->com_vid = $id_2[1];
			elseif ($id_2[0] == 'fid')
				$model->com_fid = $id_2[1];				

			
			
			
			$model->com_rid = $id_1[1];
			$model->com_author = Yii::app()->user->name;
			$model->com_email = Yii::app()->params->email;
			$model->com_status = Comment::COMMENT_PUBLISHED;	
					
			UtilTools::dump($_REQUEST);
			UtilTools::dump($model->attributes);
//			die();
			
			
			if($model->save())
				die('ok');
			else 
				die("flase");
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Comment']))
		{
			$model->attributes=$_POST['Comment'];
			if($model->save())
				die('ok');
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	public function actionBatchResource(){
		$ids = explode(',', $_POST['id']);
		$state = $_POST['ac'];
		
		//UtilTools::dump($_POST);
		//die();
		$result = array();
		
		foreach ($ids as $k=>$id)
		{
			$model = $this->loadModel($id);
			if($model->com_aid)
			{
				$article = Article::model()->findByPk($model->com_aid);
				
				if($article === null)
					throw new CHttpException(404,'The requested page does not exist.');
					
				$article->arc_iscomment = $state;
				if($article->save())
					unset($ids[$k]);
			}
			elseif ($model->com_mid)
			{
				$media = Media::model()->findByPk($model->com_mid);
				if($media===null)
					throw new CHttpException(404,'The requested page does not exist.');

				$media->media_iscomment = $state;
				if($media->save())
					unset($ids[$k]);
			}
			elseif ($model->com_gid)
			{
				$gallery = File::model()->findByPk($model->com_gid);
				if($gallery===null)
					throw new CHttpException(404,'The requested page does not exist.');
					
				$gallery->file_iscomment = $state;
				if($gallery->save())
					unset($ids[$k]);				
			}
			elseif ($model->com_vid){
				$video = File::model()->findByPk($model->com_vid);
				if($video === null)
					throw new CHttpException(404,'The requested page does not exist');
					
				$video->file_iscomment = $state;
				if($video->save())
					unset($ids[$k]);
			}
			elseif ($model->com_auid)
			{
				$audio = File::model()->findByPk($model->com_auid);
				if($audio===null)
					throw new CHttpException(404,'The requested page does not exist.');
					
				$audio->file_iscomment = $state;
				if($audio->save())
					unset($ids[$k]);
			}
		}
		
		
		echo count($ids);
		
	}
	
	public function actionBatchComments()
	{
		$ids = explode(',', $_POST['id']);
		$state = $_POST['ac'];
		
//		UtilTools::dump($_POST);
//		die();
		$result = array();
		
		foreach ($ids as $k=>$id)
		{
			$model = $this->loadModel($id);
			
			$model->com_status = $state;
			if($model->save())
				unset($ids[$k]);			
			
		}
		
		echo count($ids);
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$criteria = new CDbCriteria(array(
			'select'=>'*',			
//			'distinct'=>true,
			'group'=>'com_aid,com_mid',
			'condition'=>'com_aid IS NOT NULL OR com_mid IS NOT NULL',
			'order'=>'com_id DESC'
		));
//		UtilTools::dump($criteria);
		$dataProvider=new CActiveDataProvider('Comment',array(
			'criteria'=>$criteria
		));	
		$this->render('index',array(
			'dataProvider'=>$dataProvider
		));
	}
	
	public function actionList()
	{
		$criteria = new CDbCriteria(array(
			'select'=>'*',			
//			'distinct'=>true,
//			'group'=>'com_aid,com_mid',
			'condition'=>'com_status != '.Comment::COMMENT_TRASH,
			'order'=>'com_id DESC'
		));
//		UtilTools::dump($criteria);
		$dataProvider=new CActiveDataProvider('Comment',array(
			'criteria'=>$criteria
		));
		
		$this->render('list',array(
			'dataProvider'=>$dataProvider
		));
	}

	
	public function actionItemInfo($id)
	{
		$this->blankLayout();
		
		$model = $this->loadModel($id);
		
		$this->render('iteminfo',array(
			'data' => $model
		));
	}
	
	public function actionItemView($id)
	{
		$this->blankLayout();
		
		$model = $this->loadModel($id);
		
		$this->render('itemview',array(
			'data' => $model
		));		
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Comment('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Comment']))
			$model->attributes=$_GET['Comment'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Comment::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	protected function blankLayout()
	{
		return $this->layout='application.modules.admin.views.layouts.blank';
	}
	
	protected function baseLayout()
	{
		return $this->layout='application.modules.admin.views.layouts.base';
	}
}
